<template>
  <div>
    <el-form ref="form" :inline="true" label-width="100px" class="mt-20 searchbar-box clearfix mb-10">
      <el-button class="mr-10" @click="add('add')" type="primary" icon="el-icon-plus">添加</el-button>
      <el-button class="mr-20" type="primary" @click="importPeople()">导入</el-button>
      <label class="mr-10">姓名</label>
      <el-input v-model="searchParams.userName" placeholder="请输入姓名" class="mr-20 w-200"></el-input>
      <label class="mr-10">角色权限</label>
      <el-select v-model="searchParams.roleId" placeholder="请选择" class="mr-10 w-200">
        <el-option v-for="(item, i) in roleSelect" :key="i" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <label class="mr-10" v-show="userId === '1'">学校</label>
      <el-select v-show="userId === '1'" v-model="searchParams.schoolId" placeholder="请选择" class="mr-10 w-200"
                 clearable>
        <el-option v-for="(item, i) in schoolList" :key="i" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <el-button @click="reset">重置</el-button>
      <el-button @click="search" type="primary">确认</el-button>
    </el-form>
    <el-table :data="tableData" :empty-text="emptyText" v-loading="isLoading" element-loading-text="加载中..."
              stripe="stripe">
      <template v-for="(item, index) of tableColumn">
        <el-table-column
          :key="index + item.prop"
          :label="item.title"
          align="center"
          :show-overflow-tooltip="true"
          :min-width="item.minWidth"
          :width="item.width">
          <template slot-scope="scope">
            <span v-if="item.prop === 'roleId'">{{ getRole(scope.row.roleId) }}</span>
            <div v-else-if="item.prop === 'operation'">
              <!--<el-tooltip class="item" content="权限" placement="top-start">-->
              <!--<svg-icon class="can-click" icon-class="user" />-->
              <!--</el-tooltip>-->
              <el-tooltip class="item" content="编辑" placement="top-start">
                <svg-icon @click="add('edit', scope.row)" class="can-click" icon-class="note"/>
              </el-tooltip>
              <el-tooltip class="item" content="删除" placement="top-start">
                <svg-icon @click="handelDelete(scope.row)" class="can-click" icon-class="delete"/>
              </el-tooltip>
            </div>
            <div v-else-if="(item.prop === 'permissions') && (userId === '1')">
              <el-button @click.stop="changePermission(1, scope.row)" type="primary" size="small"
                         v-show="scope.row[item.prop] === 0">开启
              </el-button>
              <el-button @click.stop="changePermission(0, scope.row)" size="small" v-show="scope.row[item.prop] === 1"
                         style="margin-left: 0">关闭
              </el-button>
            </div>
            <span v-else>{{scope.row[item.prop]}}</span>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <el-pagination
      class="mt-30"
      :current-page="searchParams.currentPage"
      :page-size="searchParams.pageSize"
      :total="total"
      layout="sizes, total, prev, pager, next, jumper"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange">
    </el-pagination>
    <form-wrap ref="form" @submit="submit" :title="title"></form-wrap>
    <!--导入弹窗-->
    <el-dialog width="500px" title="导入" :visible.sync="importDialog" :close-on-click-modal="false"
               @close="closeDialog()">
      <el-upload
        class="upload-demo"
        ref="upload"
        :action="action"
        accept=".xlsx"
        :on-change="fileChange"
        :limit="1"
        :on-exceed="handleExceed"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :file-list="fileList"
        :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      </el-upload>
      <div class="text-center">
        <el-button @click="importDialog = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import formWrap from '@/components/form';
  import {getSession} from '@/utils'

  export default {
    name: 'user',
    components: {formWrap},
    data() {
      return {
        isLoading: false,
        emptyText: '加载中...',
        userId: getSession('userId'),
        tableColumn: [
          {title: '姓名', prop: 'userName', minWidth: '100', width: null},
          {title: '手机', prop: 'mobilePhone', width: null},
          {title: '角色权限', prop: 'roleId', minWidth: '', width: null},
          {title: '学校', prop: 'schoolName', minWidth: '', width: null},
          {title: '课程权限', prop: 'courseTitles', minWidth: '', width: null},
          {title: '下载权限', prop: 'permissions', minWidth: '100', width: ''},
          {title: '操作', prop: 'operation', minWidth: '100', width: ''}
        ],
        tableData: [],
        total: 0,
        searchParams: {
          currentPage: 1,
          pageSize: 20,
          userName: '', // 人员名称
          roleId: '', // 角色id
          schoolId: '', // 学校id
        },
        id: '',
        title: '添加',
        schoolList: [],
        roleSelect: [
          {
            label: '全部',
            value: ''
          },
          {
            label: '老师',
            value: 2
          },
          {
            label: '学生',
            value: 3
          },
          {
            label: '其他',
            value: 4
          },
          {
            label: '学校负责人',
            value: 5
          },
        ],
        importDialog: false,
        action: '',
        fileList: [],
        importData: {},
        file: null
      };
    },
    mounted() {
      this.getDataList();
      this.getSchoolList();
    },
    methods: {
      /* 获取列表数据 */
      getDataList(currentPage) {
        this.isLoading = true;
        this.searchParams.currentPage = currentPage || 1;
        let param = {
          currentPage: this.searchParams.currentPage,
          pageSize: this.searchParams.pageSize,
          id: this.id,
          userName: this.searchParams.userName,
          roleId: this.searchParams.roleId,
          schoolId: this.searchParams.schoolId,
        }
        this.$api.role.queryUserSchoolCourseList(param).then(res => {
          this.isLoading = false;
          this.total = res.total;
          this.tableData = res.data || [];
          this.emptyText = !this.tableData.length ? '暂无数据' : this.emptyText;
        });
      },
      /**
       * 获取学校列表
       **/
      getSchoolList() {
        let param = {
          currentPage: 1,
          pageSize: 999,
        };
        this.$api.basic.querySchoolCourseUserCountList(param).then(res => {
          this.schoolList = res.data || [];
          if (this.schoolList.length) {
            this.schoolList.forEach((item) => {
              this.$set(item, 'label', item.schoolName);
              this.$set(item, 'value', item.id);
            })
          }
        });
      },
      /* 新增&编辑 */
      add(type, obj) {
        // this.getRoleList();
        this.$api.role.getUserCountByRole({}).then(res => {
          let selectData = res.data;
          let selectDataArr = selectData.filter(item => item.roleId !== 1);
          let select = selectDataArr.map((item) => {
            return {
              label: item.roleName,
              value: item.roleId
            }
          });
          let labelList = [
            {label: '人员名称', prop: 'userName', type: 'input', required: true},
            {label: '角色', prop: 'roleId', type: 'select', required: true, select: select},
            {label: '学校名称', prop: 'schoolId', type: 'select', required: true, select: this.schoolList},
            {
              label: '手机号码',
              prop: 'mobilePhone',
              type: 'input',
              required: (obj ? false : true),
              disabled: (obj ? true : false)
            },
            {label: '备注', prop: 'remark', type: 'input', required: false},
          ];
          if (type === 'add') {
            this.title = '添加';
            this.$refs.form.showDialog(labelList);
          } else {
            this.title = '编辑';
            this.$refs.form.showForm(obj, labelList);
          }
        })
      },
      search() {
        this.getDataList(1);
      },
      reset() {
        this.searchParams = {
          currentPage: 1,
          pageSize: 20,
          userName: '', // 人员名称
          roleId: '', // 角色id
          schoolId: '', // 学校id
        };
        this.getDataList(1);
      },
      submit(form) {
        let param = {
          id: form.id ? form.id : '',
          userId: form.userId,
          userName: form.userName,
          roleId: form.roleId,
          schoolId: form.schoolId,
          mobilePhone: form.mobilePhone,
          remark: form.remark,
        };
        if (form.id) {
          this.$api.role.userEdit(param).then(res => {
            if (res.status.code === 200) {
              this.$message.success('编辑成功');
              this.$refs.form.cancel();
              this.getDataList();
            }
          });
        } else {
          this.$api.role.userAdd(param).then(res => {
            if (res.status.code === 200) {
              this.$message.success('添加成功');
              this.$refs.form.cancel();
              this.getDataList();
            }
          });
        }
      },
      /* 删除 */
      handelDelete(obj) {
        this.$confirm(`确定要删除${obj.userName}这个成员吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.role.userDel({
            id: obj.id,
          }).then(() => {
            this.$message({
              type: 'success',
              message: `删除成功!`
            });
            this.getDataList()
          })
        }).catch(() => {
        });
      },
      handleCurrentChange(val) {
        this.searchParams.currentPage = val
        this.getDataList(val)
      },
      handleSizeChange(val) {
        this.searchParams.pageSize = val
        this.getDataList()
      },
      getRole(val) {
        if (val === 2) {
          return '老师'
        }
        if (val === 3) {
          return '学生'
        }
        if (val === 4) {
          return '其他'
        }
        if (val === 5) {
          return '学校负责人'
        }
      },
      changePermission(val, row) {
        let param = {
          id: row.id,
          permissions: val
        };
        this.$api.role.userEdit(param).then(res => {
          if (res.status.code === 200) {
            this.$message.success(val === 0 ? '下载权限已关闭' : '下载权限已开启');
            this.getDataList();
          }
        });
      },
      /**
       * 打开导入弹窗
       **/
      importPeople() {
        if (!this.searchParams.schoolId) {
          this.$message.warning('请先选择学校！');
          return
        }
        this.importDialog = true;
      },
      closeDialog() {
        this.file = null;
        this.$refs.upload.clearFiles();
      },
      /**
       * 确定导入
       **/
      onSubmit() {
        let formData = new FormData();
        formData.append('file', this.file)
        formData.append('schoolId', this.searchParams.schoolId)
        if (this.file) {
          this.$api.course.importPeopleData(formData).then(() => {
            this.importDialog = false;
            this.$message.success('导入成功！')
            this.getDataList();
          }).catch(() => {
            this.$message.warning('导入失败！')
          })
        } else {
          this.$message.warning('请上传Excel文件！')
        }
      },
      fileChange(file) {
        this.file = file.raw;
      },
      handleExceed() {
        this.$alert('当前限制选择 1 个文件，请先移除！', {
          confirmButtonText: '确定',
          type: 'warning',
          showClose: false
        });
      },
      handlePreview() {
      },
      handleRemove() {
        this.file = null;
      },
    }
  }
</script>
<style scoped>
  .w-200 {
    width: 200px;
  }

  .upload-demo {
    height: 80px;
    display: flex;
    align-items: center;
  }
</style>
